﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PSE.Tools.SchemaComparer.Extractor;
using System.Diagnostics;
using System.IO;
using PSE.Tools.SchemaComparer.Comparer;

namespace PSE.Tools.SchemaComparer.Console
{
    //extract sinades sinamais sinawin c:\sinawin_des.xml
    //extract sinades bovwin bovwin c:\bovwin_des.xml
    //extract sinades ccowin ccowin c:\ccowin_des.xml

    //compare c:\bovwin_des.xml c:\ccowin_des.xml c:\compare_result.xml
    public class Program
    {
        static void Main(string[] args)
        {
            if (args.Length >= 2)
            {
                string mode;

                mode = args[0];

                switch (mode)
                {
                    case "extract":
                        {
                            DoExtract(args);
                        }
                        break;
                    case "compare":
                        {
                            DoCompare(args);
                        }
                        break;
                    default:
                        System.Console.WriteLine("Modo de uso: SchemaComparerConsole [mode] [parameters]");
                        break;

                }
            }
            else
                System.Console.WriteLine("Modo de uso: SchemaComparerConsole [mode] [parameter1] [parameter2] [parameter3]");

        }

        private static void DoCompare(string[] args)
        {
            string sourceSchemaFile, targetSchemaFile, compareResultFile;

            if (args.Length != 4)
            {
                System.Console.WriteLine("Modo de uso: SchemaComparerConsole compare [source schema file] [target schema file] [compare result file]");
            }
            else
            {
                bool error = false;
                sourceSchemaFile = args[1];
                targetSchemaFile = args[2];
                compareResultFile = args[3];

                if (!File.Exists(sourceSchemaFile))
                {
                    error = true;
                    System.Console.WriteLine(string.Format("File {0} not exist", sourceSchemaFile));
                }

                if (!File.Exists(targetSchemaFile))
                {
                    error = true;
                    System.Console.WriteLine(string.Format("File {0} not exist", targetSchemaFile));
                }

                if (error)
                    return;

                DBSchema sourceSchema;
                try
                {
                    sourceSchema = new DBSchema();
                    sourceSchema.LoadFromXmlFile(sourceSchemaFile);

                }
                catch (Exception ex)
                {
                    string message = string.Format("Erro ao carregar as informações de Schema do arquivo {0}.", sourceSchemaFile) + Environment.NewLine + ex.Message;
                    EventLog.WriteEntry("SchemaComparer.Comparer", message, EventLogEntryType.Error);
                    System.Console.WriteLine(message);
                    return;
                }

                DBSchema targetSchema;
                try
                {
                    targetSchema = new DBSchema();
                    targetSchema.LoadFromXmlFile(targetSchemaFile);
                }
                catch (Exception ex)
                {
                    string message = string.Format("Erro ao carregar as informações de Schema do arquivo {0}.", targetSchemaFile) + Environment.NewLine + ex.Message;
                    EventLog.WriteEntry("SchemaComparer.Comparer", message, EventLogEntryType.Error);
                    System.Console.WriteLine(message);
                    return;

                }

                DBSchemaComparer schemaComparer;
                try
                {
                    schemaComparer = new DBSchemaComparer();
                    schemaComparer.Compare(sourceSchema, targetSchema);
                }
                catch (Exception ex)
                {
                    string message = "Erro ao comparar as informações dos Schemas." + Environment.NewLine + ex.Message;
                    EventLog.WriteEntry("SchemaComparer.Comparer", message, EventLogEntryType.Error);
                    System.Console.WriteLine(message);
                    return;

                }

                try
                {
                    schemaComparer.SaveCompareResultToXmlFile(compareResultFile);
                }
                catch (Exception ex)
                {
                    string message = "Erro ao salvar o resultado da comparação dos Schemas." + Environment.NewLine + ex.Message;
                    EventLog.WriteEntry("SchemaComparer.Comparer", message, EventLogEntryType.Error);
                    System.Console.WriteLine(message);
                    return;
                }

                System.Console.WriteLine("Comparação de Schemas realizada com sucesso." + Environment.NewLine + String.Format("As divergências foram armazenadas no arquivo {0} ", compareResultFile));

            }
        }

        private static void DoExtract(string[] args)
        {
            string dataSource, user, password, destFile;

            if (args.Length != 5)
            {
                System.Console.WriteLine("Modo de uso: SchemaComparerConsole extract [data source] [user id] [password] [destination file]");
            }
            else
            {

                dataSource = args[1];
                user = args[2];
                password = args[3];
                destFile = args[4];

                DBConnectionInfo connInfo = new DBConnectionInfo()
                {
                    DataSource = dataSource,
                    User = user,
                    Password = password
                };

                DBSchema dbSchema = new DBSchema();

                try
                {
                    dbSchema.LoadDataBaseObjects(connInfo);
                }
                catch (Exception ex)
                {
                    string message = "Erro ao carregar as informações de Schema da Base de Dados." + Environment.NewLine + ex.Message;
                    EventLog.WriteEntry("SchemaComparer.Extractor", message, EventLogEntryType.Error);
                    System.Console.WriteLine(message);
                    return;
                }

                try
                {
                    dbSchema.SaveToXmlFile(destFile);
                }
                catch (Exception ex)
                {
                    string message = "Erro ao salvar as informações de Schema da Base de Dados." + Environment.NewLine + ex.Message;
                    EventLog.WriteEntry("SchemaComparer.Extractor", message, EventLogEntryType.Error);
                    System.Console.WriteLine(message);
                    return;
                }

                System.Console.WriteLine("Extração de Schema realizada com sucesso." + Environment.NewLine + " Arquivo gerado: " + destFile);
            }
        }
    }
}
